<template>
  <div>
    <main-box one="权限管理" two="角色列表">
      <!-- 栅格布局 -->
      <div>
        <el-row>
          <el-col>
            <el-button type="primary" @click="dialogVisible = true">添加角色</el-button>
          </el-col>
        </el-row>
      </div>
      <!-- 角色列表区域 -->
      <el-table :data="roleList" style="width: 100%" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1,index1) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom',index1==0 ?'bdtop':' ','vcenter']"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级分类 -->
              <el-col :span="19">
                <!-- 二级权限 -->
                <el-row
                  v-for="(item2,index2) in item1.children"
                  :key="item2.id"
                  :class="[index2==0?' ':'bdtop','vcenter'] "
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="danger"
                      v-for="(item3,index3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <!-- 操作列   -->
        <el-table-column prop="prop" label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editdialogVisible = true"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="roleDeleted(scope.row)"
            >删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="setRightsForm(scope.row)"
            >分配角色</el-button>
          </template>
        </el-table-column>
      </el-table>
    </main-box>

    <!-- 新增角色用户对话框 -->
    <el-dialog title="添加角色" :visible.sync="dialogVisible" width="50%" @close="addDialogLClosed">
      <!-- 主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="90px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="roleAdded">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色用户对话框 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editdialogVisible"
      width="50%"
      @close="closeEditDialog"
    >
      <!-- 主体区域 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="90px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editdialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>

    <!--分配角色 展示权限 -->
    <el-dialog
      title="分配权限"
      :visible.sync="showSetDialogVisible"
      width="50%"
      @close="setDialogVisibleClosed"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightsList"
        :props="rightsTreeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defkeys"
        ref="treeRef"
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="showSetDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleList: [],
      dialogVisible: false,
      addForm: {
        roleName: "",
        roleDesc: ""
      },
      addFormRules: {
        roleName: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],
        roleDesc: [{ required: true, message: "内容不能为空", trigger: "blur" }]
      },
      editdialogVisible: false,
      editForm: {
        roleName: "",
        roleDesc: ""
      },
      editFormRules: {
        roleName: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],
        roleDesc: [{ required: true, message: "内容不能为空", trigger: "blur" }]
      },
      showSetDialogVisible: false,
      rightsList: [],
      rightsTreeProps: {
        label: "authName",
        children: "children"
      },
      defkeys: [],
      roleId: ""
    };
  },
  mounted() {
    this.getRoleList();
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get("roles");
      // console.log(res);
      if (res.meta.status != 200) return this.$message.error("失败");
      this.roleList = res.data;
    },
    async removeRightById(role, rightId) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (confirmResult != "confirm") return this.$message.info("已取消删除");
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      if (res.meta.status != 200) {
        return this.$message.error("权限删除失败");
      }
      role.children = res.data;
    },
    roleAdded() {
      this.$refs.addFormRef.validate(async v => {
        if (v) {
          const { data: res } = await this.$http.post("roles", this.addForm);
          // console.log(res);
          if (res.meta.status != 201) {
            return this.$message.error("角色创建失败");
          }
          this.dialogVisible = false;
          this.getRoleList();
        }
      });
    },
    addDialogLClosed() {
      this.$refs.addFormRef.resetFields();
    },
    async roleDeleted(role) {
      console.log(role);
      const confirmResult = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (confirmResult != "confirm") return this.$message.info("已取消删除");
      const { data: res } = await this.$http.delete("roles/" + role.id);
      // console.log(res);
      if (res.meta.status != 200) {
        return this.$message.error("角色删除失败");
      }
      this.getRoleList();
      this.$message.success("删除成功");
    },
    closeEditDialog() {
      this.$refs.editFormRef.resetFields();
    },

    //编辑区域暂时不写

    async setRightsForm(role) {
      this.roleId = role.id;
      this.showSetDialogVisible = true;
      const { data: res } = await this.$http.get("rights/tree");
      // console.log(res);
      if (res.meta.status != 200) {
        return this.$message.error("分配权限失败");
      }
      //
      this.getLeafKeys(role, this.defkeys);
      this.rightsList = res.data;
    },
    // 递归
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr);
      });
    },
    setDialogVisibleClosed() {
      this.defkeys = [];
    },
    async allotRight() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      const ids = keys.join(",");

      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: ids }
      );
      // console.log(res);
      if (res.meta.status != 200) {
        return this.$message.error("失败");
      }
      this.showSetDialogVisible = false;
      this.$message.success("成功");
    }
  }
};
</script>

<style lang="less" scope>
.el-tag {
  margin: 10px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>